package com.cody.controller.answer;

import com.cody.entity.Answer;
import com.cody.entity.Comment;
import com.cody.entity.Question;
import com.cody.entity.Teacher;
import com.cody.service.AnswerService;
import com.cody.service.QuestionService;
import com.cody.service.TeacherService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * @author Cody
 * @date 2021/4/9 - 16:27
 */
@Controller
public class AnswerController {
    @Autowired
    private AnswerService answerService;
    @Autowired
    private QuestionService questionService;
    @Autowired
    private TeacherService teacherService;

    @RequestMapping("/insert/{questionId}")
    public String insert(@PathVariable("questionId") Integer questionId, HttpSession session) {
        Question question = questionService.queryQuestionByQuestionId(questionId);
        session.setAttribute("Question", question);
        return "/teacher/answer";
    }

    //提交回答
    private static String dirPath = "D:/answer";
    @PostMapping("/insertAnswer")
    public String insertAnswer(@RequestParam("content") String content,
                               @RequestParam("questionId") Integer questionId,
                               @RequestParam("blFile") MultipartFile blFile,
                               HttpSession session) throws IOException {
        if(blFile.getOriginalFilename()!=""){
            Teacher teacher = (Teacher) session.getAttribute("user");
            String fileName = blFile.getOriginalFilename();
            String suffixName = fileName.substring(fileName.lastIndexOf('.'));
            fileName = UUID.randomUUID() + suffixName;
            String pathName = dirPath + '/' + fileName;
            File file = new File(pathName);
            if (!file.getParentFile().exists()) {
                file.getParentFile().mkdirs();
            }
            blFile.transferTo(file);
            //更新
            teacher = teacherService.querySingleTeacherByTeacherNumber(teacher.getTeacherNumber());
            questionService.updateQuestion((Integer) session.getAttribute("questionId"));
            Answer answer = new Answer(1, content, teacher.getTeacherNumber(),teacher.getTeacherName(), new Date(), questionId,fileName,pathName);
            answerService.insertAnswer(answer);
        }else {
            Teacher teacher = (Teacher) session.getAttribute("user");
            //更新
            teacher = teacherService.querySingleTeacherByTeacherNumber(teacher.getTeacherNumber());
            //空指针
            Answer answer = new Answer(1, content, teacher.getTeacherNumber(),teacher.getTeacherName(), new Date(), questionId,"-1","-1");
            questionService.updateQuestion(questionId);
            answerService.insertAnswer(answer);
        }

         return "redirect:/teacher/index";
    }

    @RequestMapping("/answer/del")
    @ResponseBody
    public Map<String, String> del(@RequestParam(required = false, name = "answerId") int answerId) {
        Map<String, String> map = new HashMap<>();
        boolean flag =  answerService.delAnswerByAnswerId(answerId);
        if(flag){
            map.put("msg","删除成功");
        }
        return map;
    }
    @RequestMapping("/answer/download/{anwserId}")
    public void download(@PathVariable("anwserId") Integer anwserId,
                         HttpServletResponse response) throws IOException {
        Answer answer = answerService.queryAllAnswerByAnswerId(anwserId);
        String pathName = answer.getAnswerPicPath();
        File file = new File(pathName);
        response.reset();
        response.setContentType("application/octet-stream");
        response.setCharacterEncoding("utf-8");
        response.setContentLength((int) file.length());
        response.setHeader("Content-Disposition", "attachment;filename=" + answer.getAnswerPicName());
        BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
        byte[] buff = new byte[1024];
        OutputStream os = response.getOutputStream();
        int i = 0;
        while ((i = bis.read(buff)) != -1) {
            os.write(buff, 0, i);
            os.flush();
        }
    }
    @RequestMapping("/answer/update")
    public String update(@RequestParam(required = false, name = "answerId") String answerId,
                         @RequestParam(required = false, name = "answerText") String answerText,
                         HttpSession session) {

        Answer answer = answerService.queryAllAnswerByAnswerId(Integer.parseInt(answerId));
        answer.setAnswerText(answerText);
        answerService.updAnswerInfo(answer);
        return "redirect:/admin/index";
    }


}
